package com.wl.video.live.activity;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.TextHttpResponseHandler;
import com.netease.LSMediaCapture.lsMediaCapture;
import com.netease.vcloud.video.effect.VideoEffect;
import com.wl.video.live.AppContext;
import com.wl.video.live.R;
import com.wl.video.live.api.LiveAPI;
import com.wl.video.live.bean.ChannelBean;
import com.wl.video.live.entity.LiveChannelEntity;
import com.wl.video.live.utils.DialogHelp;
import com.wl.video.live.utils.TimeZoneUtil;

import java.io.Serializable;
import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

import static com.netease.LSMediaCapture.lsMediaCapture.FormatType.RTMP;
import static com.netease.LSMediaCapture.lsMediaCapture.StreamType.AV;

public class ConfigActivity extends Activity {
    private PublishParam publishParam = null;
    private ConfigActivity.MsgReceiver msgReceiver = null;

    @Bind(R.id.main_start_create)
    protected Button mainStartBtn;

    @Bind(R.id.main_video_date)
    protected TextView main_video_date;

    @Bind(R.id.main_video_time)
    protected TextView main_video_time;

    @Bind(R.id.main_video_num)
    protected EditText main_video_num;

    int mYear, mMonth, mDay;
    private ProgressDialog waitDialog;
    //test
    //    @Bind(R.id.main_format_type)
//    protected RadioGroup mainStreamType;
//
//    @Bind(R.id.main_radiogroup_resolution)
//    protected RadioGroup mainResolution;
//
//    @Bind(R.id.main_label_video_path)
//    protected TextView labelVideo;
//
//    @Bind(R.id.main_video_path)
//    protected EditText videoPath;
//
//    @Bind(R.id.main_screen_scale)
//    protected RadioGroup mainScreenScale;
//    private DateFormat formatter_file_name = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault());


    public class InputFilterMinMax implements InputFilter {
        private int min, max;

        public InputFilterMinMax(int min, int max) {
            this.min = min;
            this.max = max;
        }

        public InputFilterMinMax(String min, String max) {
            this.min = Integer.parseInt(min);
            this.max = Integer.parseInt(max);
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            try {
                int input = Integer.parseInt(dest.toString() + source.toString());
                if (isInRange(min, max, input))
                    return null;
            } catch (Exception nfe) {
            }
            return "";
        }

        private boolean isInRange(int a, int b, int c) {
            return b > a ? c >= a && c <= b : c >= b && c <= a;
        }
    }

    public static class PublishParam implements Serializable {
        String pushUrl = null; //推流地址
        lsMediaCapture.StreamType streamType = AV;  // 推流类型
        lsMediaCapture.FormatType formatType = RTMP; // 推流格式
        String recordPath; //文件录制地址，当formatType 为 MP4 或 RTMP_AND_MP4 时有效
        lsMediaCapture.VideoQuality videoQuality = lsMediaCapture.VideoQuality.HIGH;//清晰度
        boolean isScale_16x9 = true; //是否强制16:9
        boolean useFilter = false; //是否使用滤镜
        boolean frontCamera = false; //是否默认前置摄像头
        boolean watermark = false; //是否添加水印
        boolean qosEnable = false;  //是否开启QOS
        boolean graffitiOn = false; //是否添加涂鸦
        boolean uploadLog = true; //是否上传SDK运行日志
        VideoEffect.FilterType filterType = VideoEffect.FilterType.clean; //滤镜类型
    }

    //用于接收Service发送的消息
    public class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            int value = intent.getIntExtra("LiveStreamingStopFinished", 0);
            if (value == 1)//finished
            {
                mainStartBtn.setEnabled(true);
                mainStartBtn.setText("进入直播");
            } else//not yet finished
            {
                mainStartBtn.setEnabled(false);
                mainStartBtn.setText("直播停止中...");
            }
        }
    }

    protected void showDialog() {
        if (waitDialog == null) {
            waitDialog = DialogHelp.getWaitDialog(this, getString(R.string.saving));
        }
        waitDialog.setCancelable(false);
        waitDialog.setCanceledOnTouchOutside(false);
        waitDialog.show();
    }

    protected void hideDialog() {
        if (waitDialog != null) {
            waitDialog.dismiss();
        }
    }

    @OnClick(R.id.main_video_date)
    protected void choseDate() {
        Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);
        new DatePickerDialog(ConfigActivity.this, onDateSetListener, mYear, mMonth, mDay).show();
    }

    @OnClick(R.id.main_video_time)
    protected void choseTime() {
        Calendar ca = Calendar.getInstance();
//        Toast.makeText(getApplication(), "当前时间==="+ca.get(Calendar.HOUR_OF_DAY), Toast.LENGTH_LONG).show();

        showTimePickerDialog(this, main_video_time, ca);
    }

    /**
     * 日期选择器对话框监听
     */
    private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            String days;
            if (mMonth + 1 < 10) {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("-").append("0").
                            append(mMonth + 1).append("-").append("0").append(mDay).append("").toString();
                } else {
                    days = new StringBuffer().append(mYear).append("-").append("0").
                            append(mMonth + 1).append("-").append(mDay).append("").toString();
                }

            } else {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("-").
                            append(mMonth + 1).append("-").append("0").append(mDay).append("").toString();
                } else {
                    days = new StringBuffer().append(mYear).append("-").
                            append(mMonth + 1).append("-").append(mDay).append("").toString();
                }

            }
            main_video_date.setText(days);
        }
    };

    public static void showTimePickerDialog(Activity activity, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog(activity, android.R.style.Theme_DeviceDefault_Light_Dialog,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view,
                                          int hourOfDay, int minute) {
                        //使用三元运算符来满足需求
                        String sHour = hourOfDay < 10 ? "0" + hourOfDay : "" + hourOfDay;
                        String sMinutes = minute < 10 ? "0" + minute : ""
                                + minute;
                        tv.setText(sHour + ":" + sMinutes);
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                , true).show();
    }

    @OnClick(R.id.main_start_create)
    protected void startLive() {
        //检查参数是否完整
        String liveDate = main_video_date.getText().toString();
        String liveTime = main_video_time.getText().toString();
        String liveNum = main_video_num.getText().toString();


        if (null == liveDate || liveDate.trim().length() == 0) {
            Toast.makeText(getApplication(), "请选择直播日期！", Toast.LENGTH_LONG).show();
            return;
        } else {
            String today = TimeZoneUtil.getCurrentTime("yyyy-MM-dd");
            String diff = TimeZoneUtil.getTimedifference(liveDate, today, "yyyy-MM-dd");

            long di = Long.valueOf(diff);
            if (di < 0) {
                Toast.makeText(getApplication(), "直播日期不能早于今天！", Toast.LENGTH_LONG).show();
                return;
            } else if (di == 0) {
                if (null == liveTime || liveTime.trim().length() == 0) {
                    Toast.makeText(getApplication(), "请选择直播时间！", Toast.LENGTH_LONG).show();
                    return;
                } else {
                    today = TimeZoneUtil.getCurrentTime("yyyy-MM-dd HH:mm");
                    diff = TimeZoneUtil.getTimedifference(liveDate + " " + liveTime, today, "yyyy-MM-dd HH:mm");
                    long di2 = Long.valueOf(diff);
                    if (di2 < 0 || di2 == 0) {
                        Toast.makeText(getApplication(), "直播时间不能早于当前时间！", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
            }
        }

        if (null == liveNum || liveNum.trim().length() == 0) {
            Toast.makeText(getApplication(), "请填写直播人数！", Toast.LENGTH_LONG).show();
            return;
        }

        LiveChannelEntity liveChannelEntity = new LiveChannelEntity();
        liveChannelEntity.setLiveDate(liveDate);
        liveChannelEntity.setLiveTime(liveTime);
        liveChannelEntity.setLiveNum(liveNum);
        liveChannelEntity.setDeviceId(AppContext.getInstance().getAppId());

        showDialog();
        LiveAPI.getLiveChannel(liveChannelEntity, channelHandler);
//        publishParam.pushUrl = "rtmp://pa569d9b7.live.126.net/live/6e989876ec57480b806f943ddf2f288f?wsSecret=73e05dfcecd4f430c92dc7169226bef5&wsTime=1546422684";
//        Intent intent = new Intent(ConfigActivity.this, LiveActivity.class);
//        intent.putExtra("data", publishParam);
//        startActivity(intent);
//
//        Intent intent = new Intent(ConfigActivity.this, ShowActivity.class);
//        startActivity(intent);
//        finish();
    }

    @OnClick(R.id.iv_back)
    protected void back() {
//        Intent intent = new Intent(ConfigActivity.this, MainActivity.class);
//        startActivity(intent);
        finish();
    }

    private final TextHttpResponseHandler channelHandler = new TextHttpResponseHandler() {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            hideDialog();

            Toast.makeText(getApplication(), "获取直播频道失败，请重新尝试！", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            hideDialog();
            //获取直播推流地址，频道号，考虑记录在本地
            if (statusCode == 200) {
                StringBuilder builder = new StringBuilder();
                builder.append(responseString);
                String builder_BOM = jsonTokener(builder.toString());
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject = JSONObject.parseObject(builder_BOM);
                    String code = jsonObject.getString("success");
                    if (code.trim().equals("true")) {
                        String body = jsonObject.getString("data");
                        jsonObject = JSONObject.parseObject(body);
                        body = jsonObject.getString("channel");
                        ChannelBean channelBean = JSON.parseObject(body, ChannelBean.class);

                        //播放地址
                        AppContext.getInstance().setProperty("live_play_path", channelBean.getLiveUrl());
                        //邀请码
                        AppContext.getInstance().setProperty("live_play_code", channelBean.getInviteCode());

                        Intent intent = new Intent(ConfigActivity.this, ShowActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(getApplication(), "获取直播频道失败，请重新尝试！", Toast.LENGTH_LONG).show();
                    }

                } catch (Exception e) {
                    Toast.makeText(getApplication(), "获取直播频道失败，请重新尝试！", Toast.LENGTH_LONG).show();
                }
            } else {

            }


//            Intent intent = new Intent(ConfigActivity.this, LiveActivity.class);
//            intent.putExtra("data", publishParam);
//            startActivity(intent);

//            Intent intent = new Intent(ConfigActivity.this, ShowActivity.class);
//            startActivity(intent);
        }
    };

    protected String jsonTokener(String in) {
        if (in != null && in.startsWith("\ufeff")) {
            in = in.substring(1);
        }
        return in;
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_config);
        ButterKnife.bind(this);

        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("LiveStreamingStopFinished");
        registerReceiver(msgReceiver, intentFilter);
        publishParam = new PublishParam();
        main_video_num.setFilters(new InputFilter[]{new InputFilterMinMax("1", "9999")});


//        publishParam.recordPath = "/sdcard/111/" + formatter_file_name.format(new Date()) + ".mp4";
//        videoPath.setText(publishParam.recordPath);
//
//        RadioGroup formatGroup = (RadioGroup) findViewById(R.id.main_format_type);
//        formatGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
//                switch (checkedId) {
//                    case R.id.main_format_rtmp:
//                        publishParam.formatType = lsMediaCapture.FormatType.RTMP;
//                        labelVideo.setVisibility(View.GONE);
//                        videoPath.setVisibility(View.GONE);
//                        break;
//                    case R.id.main_format_mp4:
//                        publishParam.formatType = lsMediaCapture.FormatType.MP4;
//                        labelVideo.setVisibility(View.VISIBLE);
//                        videoPath.setVisibility(View.VISIBLE);
//                        break;
//                    case R.id.main_format_rtmp_and_mp4:
//                        publishParam.formatType = lsMediaCapture.FormatType.RTMP_AND_MP4;
//                        labelVideo.setVisibility(View.VISIBLE);
//                        videoPath.setVisibility(View.VISIBLE);
//                        break;
//                    default:
//                        publishParam.formatType = lsMediaCapture.FormatType.RTMP;
//                        labelVideo.setVisibility(View.GONE);
//                        videoPath.setVisibility(View.GONE);
//                        break;
//                }
//            }
//        });

//        RadioGroup resolutionGroup = (RadioGroup) findViewById(R.id.main_radiogroup_resolution);
//        resolutionGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
//                switch (checkedId) {
//                    case R.id.main_resolution_super:
//                        publishParam.videoQuality = lsMediaCapture.VideoQuality.SUPER;
//                        break;
//                    case R.id.main_resolution_high:
//                        publishParam.videoQuality = lsMediaCapture.VideoQuality.HIGH;
//                        break;
//                    case R.id.main_resolution_medium:
//                        publishParam.videoQuality = lsMediaCapture.VideoQuality.MEDIUM;
//                        break;
//                    default:
//                        publishParam.videoQuality = lsMediaCapture.VideoQuality.HIGH;
//                        break;
//                }
//            }
//        });
//
//        RadioGroup scaleGroup = (RadioGroup) findViewById(R.id.main_screen_scale);
//        scaleGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
//                switch (checkedId) {
//                    case R.id.main_scale_16x9:
//                        publishParam.isScale_16x9 = true;
//                        break;
//                    case R.id.main_scale_normal:
//                        publishParam.isScale_16x9 = false;
//                        break;
//                    default:
//                        break;
//                }
//            }
//        });
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(msgReceiver);
        msgReceiver = null;
        super.onDestroy();
    }
}
